package com.study.jvm;

import com.study.jvm.classloader.Person;
import javassist.*;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;

import java.lang.reflect.Method;

/**
 * Description:
 * User: Administrator
 * DateTime: 2017/7/4 0004 21:05
 */
public class GetParamNamesByJavassist {
    public static void main(String[] args) throws NotFoundException {
        Method[] methods = Person.class.getDeclaredMethods();
        Class clazz = methods[0].getDeclaringClass();
        System.out.println(clazz);

        ClassPool classPool = ClassPool.getDefault();
        classPool.insertClassPath(new ClassClassPath(clazz));

        //TODO 方法什么时候返回null， 什么时候抛出notfound异常？
        CtClass ctClass = classPool.get(clazz.getName());

        CtMethod ctMethod = ctClass.getDeclaredMethod("setName");
        MethodInfo methodInfo = ctMethod.getMethodInfo();

        CodeAttribute codeAttribute = methodInfo.getCodeAttribute();

        LocalVariableAttribute attribute = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
        if (attribute == null) {
            System.out.println("params  is null");
        }

        String[] paramNames = new String[ctMethod.getParameterTypes().length];
        int pos = Modifier.isStatic(ctMethod.getModifiers()) ? 0 : 1;

        for (int i = 0; i < paramNames.length; i++)
            paramNames[i] = attribute.variableName(i + pos);
        for (int i = 0; i < paramNames.length; i++) {
            System.out.println(paramNames[i]);
        }

    }
}
